﻿// ReSharper disable SuggestUseVarKeywordEvident
using System;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
using bnab.DataModel;

namespace bnab
{
  static class Program
  {
    private static ControlContaner _container;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
      bool alertOnly = 
        args.Length > 0 && 
        string.Compare(args[0], "alertonly", true) == 0;

      
      if (alertOnly)
      {
        CheckBalanceAlertOnly();
      }
      else
      {
        Initialize();
        Application.EnableVisualStyles();
        Application.Run();
      }
    }

    private static void CheckBalanceAlertOnly()
    {
      if (!Settings.Valid)
      {
        MessageBox.Show(
          "Неправильные настройки. Запустите программу в обычном режиме и введите корректные параметры",
          "Деловая Сеть",
          MessageBoxButtons.OK,
          MessageBoxIcon.Error,
          MessageBoxDefaultButton.Button1);

        return;
      }

      try
      {
        Account acc = new Account();
        float balance = acc.GetBalance();

        if (balance <= Settings.BalanceWarning)
        {
          MessageBox.Show(
            string.Format(Thread.CurrentThread.CurrentUICulture, "Ваш баланс: {0:N2} руб.", balance),
            "Деловая Сеть",
            MessageBoxButtons.OK,
            MessageBoxIcon.Warning,
            MessageBoxDefaultButton.Button1);
        }
      }
      catch (Exception exception)
      {
        MessageBox.Show(
          "Ошибка при проверке баланса:\r\n" + exception.Message,
          "Деловая Сеть",
          MessageBoxButtons.OK,
          MessageBoxIcon.Error,
          MessageBoxDefaultButton.Button1);
      }
    }

    #region Event handlers

    private static void miExit_Click(object sender, EventArgs e)
    {
      _container.Dispose();
      Application.Exit();
    }

    private static void miSettings_Click(object sender, EventArgs e)
    {
      ShowSettingsForm();
    }

    private static void ShowSettingsForm()
    {
      _container.CheckTimer.Stop();
      _container.miSettings.Enabled = false;
      using (Form f = new SettingsForm())
      {
        if (f.ShowDialog() == DialogResult.OK && Settings.Valid)
        {
          InvokeCheckBalance(false);
        }
      }
      _container.miSettings.Enabled = true;
    }

    private static void miCheckBalance_Click(object sender, EventArgs e)
    {
      InvokeCheckBalance(true);
    }

    private static void InvokeCheckBalance(bool forceTooltip)
    {
      if (_container.BgWorker.IsBusy)
      {
        return;
      }
      _container.TrayIcon.Icon = _container.BnIconHybrid;
      WorkerData wd = new WorkerData
                        {
                          Worker = _container.BgWorker,
                          ForceTooltip = forceTooltip
                        };
      _container.BgWorker.RunWorkerAsync(wd);
    }

    #endregion


    private static void Initialize()
    {
      _container = new ControlContaner();
      _container.miExit.Click += miExit_Click;
      _container.miSettings.Click += miSettings_Click;
      _container.miCheckBalance.Click += miCheckBalance_Click;
      _container.BgWorker.DoWork += BgWorker_DoWork;
      _container.BgWorker.RunWorkerCompleted += BgWorker_RunWorkerCompleted;
      _container.CheckTimer.Interval = 1000 * 60 * 2;
      _container.CheckTimer.Tick += CheckTimer_Tick;

      if (Settings.Valid)
      {
        InvokeCheckBalance(false);
      }
      else
      {
        ShowSettingsForm();
      }
    }

    static void CheckTimer_Tick(object sender, EventArgs e)
    {
      InvokeCheckBalance(false);
    }

    static void BgWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
      WorkerData wd = (WorkerData)e.Result;

      if (!wd.Sucess)
      {
        _container.TrayIcon.BalloonTipIcon = ToolTipIcon.Error;
        _container.TrayIcon.BalloonTipText = "Произошла ошибка:\r\n" + wd.Error;
        _container.TrayIcon.Icon = _container.BnIconRed;

        _container.TrayIcon.Text = "Сбой: " + wd.Error;

        _container.TrayIcon.ShowBalloonTip(20 * 1000);
      }
      else
      {
        CultureInfo cultureInfo = new CultureInfo("ru-RU");
        _container.TrayIcon.BalloonTipText = string.Format("Баланс: {0} руб.",
                                                           wd.Balance.ToString("N2", cultureInfo));

        _container.TrayIcon.Text = string.Format("Баланс: {0} руб.",
                                                 wd.Balance.ToString("N2", cultureInfo));

        if (wd.Balance <= Settings.BalanceWarning)
        {
          _container.TrayIcon.BalloonTipIcon = ToolTipIcon.Warning;
          _container.TrayIcon.Icon = _container.BnIconRed;
          _container.TrayIcon.ShowBalloonTip(10 * 1000);
        }
        else
        {
          _container.TrayIcon.BalloonTipIcon = ToolTipIcon.Info;
          _container.TrayIcon.Icon = _container.BnIconGreen;
          if (wd.ForceTooltip)
          {
            _container.TrayIcon.ShowBalloonTip(5 * 1000);
          }
        }
      }
    }

    static void BgWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
      WorkerData wd = (WorkerData)e.Argument;

      try
      {
        Account acc = new Account();
        wd.Balance = acc.GetBalance();
        wd.Sucess = true;
        wd.Error = null;
      }
      catch (Exception exception)
      {
        wd.Sucess = false;
        wd.Error = exception.Message;
      }
      e.Result = wd;
    }
  }
}
// ReSharper restore SuggestUseVarKeywordEvident
